package com.gshrms.service;

import com.gshrms.common.core.domain.AjaxResult;
import com.gshrms.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 发送限制key前缀 
    private static final String SEND_LIMIT_KEY = "sms:limit:%s";
    // 验证码存储key前缀 
    private static final String CODE_KEY = "sms:code:%s";
    // 24小时限制次数 
    private static final int MAX_SEND_TIMES = 5;
    // 验证码有效期(5分钟)
    private static final long CODE_EXPIRE = 5 * 60;

    public boolean sendCode(String phone) {
        // 1. 检查24小时内发送次数 
        String limitKey = String.format(SEND_LIMIT_KEY, phone);
        Long sendCount = redisTemplate.opsForValue().increment(limitKey, 1);

        // 首次发送设置24小时过期 
        if (sendCount != null && sendCount == 1) {
            redisTemplate.expire(limitKey, 24, TimeUnit.HOURS);
        }

        // 超过限制次数 
        if (sendCount != null && sendCount > MAX_SEND_TIMES) {
            throw new ServiceException("今日发送次数已达上限");
        }

        // 2. 生成并存储验证码(自动覆盖旧值)
        String code = generateRandomCode();
        String codeKey = String.format(CODE_KEY, phone);
        redisTemplate.opsForValue().set(codeKey, code, CODE_EXPIRE, TimeUnit.SECONDS);

        // 3. 调用短信服务发送验证码 
        boolean sendResult = sendSms(phone, code);
        if (!sendResult) {
            throw new ServiceException("发送短信失败");
        }
        return sendResult;
    }

    // 验证验证码 
    public boolean verifyCode(String phone, String inputCode) {
        String codeKey = String.format(CODE_KEY, phone);
        String storedCode = redisTemplate.opsForValue().get(codeKey);
        return inputCode != null && inputCode.equals(storedCode);
    }

    // 生成6位随机数字 
    private String generateRandomCode() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    // 模拟短信发送 
    private boolean sendSms(String phone, String code) {
        // 实际项目替换为真实短信服务调用 
        System.out.printf(" 向%s发送验证码：%s%n", phone, code);
        return true;
    }


}